package misc

import lexpar.LexingRegexParsers

//object SimpleScala extends RegexParsers {
object SimpleScala extends LexingRegexParsers {
  literal("class", "def", "extends", "type", "val", "var")
  literal("(", ")", "{", "}", ",", ":", "=", ".")
  literal("+", "-", "*", "/")
  
  val ID: Parser[String] = """[a-zA-Z]([a-zA-Z0-9]|_[a-zA-Z0-9])*""".r
  val NUM: Parser[String] = """[1-9][0-9]*""".r
 
  def program = clazz+
  def classPrefix = "class" ~ ID ~ "(" ~ formals ~ ")"
  def classExt = "extends" ~ ID ~ "(" ~ actuals ~ ")"
  def clazz = classPrefix ~ opt(classExt) ~ "{" ~ (member+) ~ "}"
  def formals = repsep(ID ~ ":" ~ ID, ",")
  def actuals = repsep(expr, ",")//expr*
 
  def member = (
      "val" ~ ID ~ ":" ~ ID ~ "=" ~ expr
    | "var" ~ ID ~ ":" ~ ID ~ "=" ~ expr
    | "def" ~ ID ~ "(" ~ formals ~ ")" ~ ":" ~ ID ~ "=" ~ expr
    | "def" ~ ID ~ ":" ~ ID ~ "=" ~ expr
    | "type" ~ ID ~ "=" ~ ID
  )
 
  def expr: Parser[Any] = term ~ rep("+" ~ term | "-" ~ term)
  def term: Parser[Any] = factor ~ rep("*" ~ factor | "/" ~ factor)
  def factor: Parser[Any] = ID | NUM | "(" ~ expr ~ ")" | ID ~ ("." ~ ID ~ "(" ~ actuals ~ ")")+
//  def factor = term ~ ("." ~ ID ~ "(" ~ actuals ~ ")")*

  val p1 = """
    class MyClass(msg: String) extends RegexParsers() {
      val c2: Int = 3 + 4
      var done: Boolean = false
      def sqr(x: Double): Double = x * x
      def sqrt(a: Double): Double = sqrt(a)
    }
  """

  def main(args: Array[String]) {
    //traceTokens = true
    val pr = parseAll(program, p1)
    println(pr)
  }
}